package com.acyouzi.leetcode.string;

import java.util.Arrays;

/**
 * 17/9/16 21:39
 *
 * @author sunxu
 */
public class NextGreaterElement {
  public int nextGreaterElement(int n) {
    char[] arr = String.valueOf(n).toCharArray();
    int index = -1;
    int min = arr.length-1;
    for (int i = arr.length-1; i > 0; i--) {
      if (arr[i] > arr[i-1]){
        index = i-1;
        break;
      }
    }
    if (index == -1) return index;
    int max = 0;
    for (int i = arr.length-1; i > index; i--) {
      if (arr[i] > arr[index]) {
        max = i;
        break;
      }
    }
    char tmp = arr[index];
    arr[index] = arr[max];
    arr[max] = tmp;
    Arrays.sort(arr,index+1,arr.length);
    long res = Long.parseLong(String.valueOf(arr));
    return res <= Integer.MAX_VALUE ? (int)res : -1;
  }
}
